package com.example.spdemo;

import com.example.spdemo.entity.User;
import com.example.spdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

@Component
public class ConsoleUserManager implements CommandLineRunner {

    @Autowired
    private UserService userService;

    @Override
    public void run(String... args) throws Exception {
        // 尝试设置控制台编码为UTF-8
        try {
            System.setOut(new PrintStream(System.out, true, StandardCharsets.UTF_8.name()));
        } catch (UnsupportedEncodingException e) {
            System.out.println("无法设置UTF-8编码: " + e.getMessage());
        }
        
        Scanner scanner;
        try {
            scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            scanner = new Scanner(System.in);
            System.out.println("警告：可能无法正确处理中文字符");
        }
        
        boolean running = true;

        System.out.println("=========================================");
        System.out.println("    欢迎使用用户管理系统控制台版本");
        System.out.println("=========================================");

        while (running) {
            showMenu();
            System.out.print("请选择操作 (输入数字): ");
            String choice = scanner.nextLine().trim();

            switch (choice) {
                case "1":
                    listAllUsers();
                    break;
                case "2":
                    getUserById(scanner);
                    break;
                case "3":
                    createUser(scanner);
                    break;
                case "4":
                    updateUser(scanner);
                    break;
                case "5":
                    deleteUser(scanner);
                    break;
                case "0":
                    running = false;
                    System.out.println("感谢使用用户管理系统，再见！");
                    break;
                default:
                    System.out.println("无效选项，请重新选择。");
            }

            if (running) {
                System.out.println("\n按回车键继续...");
                scanner.nextLine();
            }
        }

        scanner.close();
    }

    private void showMenu() {
        System.out.println("\n---------- 用户管理系统主菜单 ----------");
        System.out.println("1. 查看所有用户");
        System.out.println("2. 根据ID查询用户");
        System.out.println("3. 创建新用户");
        System.out.println("4. 更新用户信息");
        System.out.println("5. 删除用户");
        System.out.println("0. 退出系统");
        System.out.println("-------------------------------------");
    }

    private void listAllUsers() {
        System.out.println("\n---------- 所有用户列表 ----------");
        try {
            List<User> users = userService.findAll();
            if (users.isEmpty()) {
                System.out.println("暂无用户数据");
            } else {
                System.out.printf("%-5s %-15s %-15s %-20s %-15s %-30s%n", "ID", "用户名", "昵称", "邮箱", "电话", "地址");
                System.out.println("----------------------------------------------------------------------------------------------");
                for (User user : users) {
                    // 打印原始数据以诊断编码问题
                    System.out.printf("%-5d %-15s %-15s %-20s %-15s %-30s%n",
                            user.getId(),
                            user.getUsername(),
                            user.getNickname(),
                            user.getEmail(),
                            user.getPhone(),
                            user.getAddress() != null ? user.getAddress() : "");
                }
            }
        } catch (Exception e) {
            System.out.println("查询用户列表失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void getUserById(Scanner scanner) {
        System.out.println("\n---------- 查询用户 ----------");
        System.out.print("请输入用户ID: ");
        try {
            String idStr = scanner.nextLine().trim();
            Integer id = Integer.parseInt(idStr);
            User user = userService.findById(id);
            if (user != null) {
                System.out.println("\n用户详情:");
                System.out.println("ID: " + user.getId());
                System.out.println("用户名: " + user.getUsername());
                System.out.println("昵称: " + user.getNickname());
                System.out.println("邮箱: " + user.getEmail());
                System.out.println("电话: " + user.getPhone());
                System.out.println("地址: " + (user.getAddress() != null ? user.getAddress() : ""));
            } else {
                System.out.println("未找到ID为 " + id + " 的用户");
            }
        } catch (NumberFormatException e) {
            System.out.println("输入的ID格式不正确");
        } catch (Exception e) {
            System.out.println("查询用户失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void createUser(Scanner scanner) {
        System.out.println("\n---------- 创建新用户 ----------");
        try {
            User user = new User();
            
            System.out.print("请输入用户名: ");
            user.setUsername(scanner.nextLine().trim());
            
            System.out.print("请输入密码: ");
            user.setPassword(scanner.nextLine().trim());
            
            System.out.print("请输入昵称: ");
            user.setNickname(scanner.nextLine().trim());
            
            System.out.print("请输入邮箱: ");
            user.setEmail(scanner.nextLine().trim());
            
            System.out.print("请输入电话: ");
            user.setPhone(scanner.nextLine().trim());
            
            System.out.print("请输入地址: ");
            String address = scanner.nextLine().trim();
            System.out.println("您输入的地址是: " + address); // 调试输出
            user.setAddress(address);

            int result = userService.save(user);
            if (result > 0) {
                System.out.println("用户创建成功!");
            } else {
                System.out.println("用户创建失败!");
            }
        } catch (Exception e) {
            System.out.println("创建用户失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void updateUser(Scanner scanner) {
        System.out.println("\n---------- 更新用户信息 ----------");
        try {
            System.out.print("请输入要更新的用户ID: ");
            String idStr = scanner.nextLine().trim();
            Integer id = Integer.parseInt(idStr);
            
            User existingUser = userService.findById(id);
            if (existingUser == null) {
                System.out.println("未找到ID为 " + id + " 的用户");
                return;
            }

            User user = new User();
            user.setId(id);
            
            System.out.print("请输入新用户名 (当前: " + existingUser.getUsername() + "): ");
            String username = scanner.nextLine().trim();
            user.setUsername(username.isEmpty() ? existingUser.getUsername() : username);
            
            System.out.print("请输入新密码 (当前: " + existingUser.getPassword() + "): ");
            String password = scanner.nextLine().trim();
            user.setPassword(password.isEmpty() ? existingUser.getPassword() : password);
            
            System.out.print("请输入新昵称 (当前: " + existingUser.getNickname() + "): ");
            String nickname = scanner.nextLine().trim();
            user.setNickname(nickname.isEmpty() ? existingUser.getNickname() : nickname);
            
            System.out.print("请输入新邮箱 (当前: " + existingUser.getEmail() + "): ");
            String email = scanner.nextLine().trim();
            user.setEmail(email.isEmpty() ? existingUser.getEmail() : email);
            
            System.out.print("请输入新电话 (当前: " + existingUser.getPhone() + "): ");
            String phone = scanner.nextLine().trim();
            user.setPhone(phone.isEmpty() ? existingUser.getPhone() : phone);
            
            System.out.print("请输入新地址 (当前: " + existingUser.getAddress() + "): ");
            String address = scanner.nextLine().trim();
            System.out.println("您输入的新地址是: " + address); // 调试输出
            user.setAddress(address.isEmpty() ? existingUser.getAddress() : address);

            int result = userService.save(user);
            if (result > 0) {
                System.out.println("用户信息更新成功!");
            } else {
                System.out.println("用户信息更新失败!");
            }
        } catch (NumberFormatException e) {
            System.out.println("输入的ID格式不正确");
        } catch (Exception e) {
            System.out.println("更新用户信息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void deleteUser(Scanner scanner) {
        System.out.println("\n---------- 删除用户 ----------");
        try {
            System.out.print("请输入要删除的用户ID: ");
            String idStr = scanner.nextLine().trim();
            Integer id = Integer.parseInt(idStr);
            
            User user = userService.findById(id);
            if (user == null) {
                System.out.println("未找到ID为 " + id + " 的用户");
                return;
            }
            
            System.out.println("确认删除用户 " + user.getUsername() + " 吗? (y/N)");
            String confirm = scanner.nextLine().trim();
            
            if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
                int result = userService.deleteById(id);
                if (result > 0) {
                    System.out.println("用户删除成功!");
                } else {
                    System.out.println("用户删除失败!");
                }
            } else {
                System.out.println("取消删除操作");
            }
        } catch (NumberFormatException e) {
            System.out.println("输入的ID格式不正确");
        } catch (Exception e) {
            System.out.println("删除用户失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}